/*
 * Copyright (C) 2017 skydoves
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.skydoves.powermenudemo;

import com.skydoves.powermenu.CircularEffect;
import com.skydoves.powermenu.CustomPowerMenu;
import com.skydoves.powermenu.MenuAnimation;
import com.skydoves.powermenu.OnDismissedListener;
import com.skydoves.powermenu.OnMenuItemClickListener;
import com.skydoves.powermenu.PowerMenu;
import com.skydoves.powermenu.PowerMenuItem;
import com.skydoves.powermenu.TransPowerMenu;
import com.skydoves.powermenudemo.customs.adapters.CenterMenuAdapter;
import com.skydoves.powermenudemo.customs.adapters.CustomDialogMenuAdapter;
import com.skydoves.powermenudemo.customs.items.NameCardMenuItem;

import ohos.aafwk.ability.ILifecycle;
import ohos.aafwk.ability.Lifecycle;
import ohos.agp.components.element.PixelMapElement;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;
import java.util.Optional;

public class PowerMenuUtils {
    public static PowerMenu getHamburgerPowerMenu(
            Context context,
            ILifecycle lifecycleOwner,
            OnMenuItemClickListener<PowerMenuItem> onMenuItemClickListener,
            OnDismissedListener onDismissedListener) {
        return new PowerMenu.Builder(context)
                .addItem(new PowerMenuItem("Novel", true))
                .addItem(new PowerMenuItem("Poetry", false))
                .addItem(new PowerMenuItem("Art", false))
                .addItem(new PowerMenuItem("Journals", false))
                .addItem(new PowerMenuItem("Travel", false))
                .setAutoDismiss(true)
                .setLifecycle(lifecycleOwner)
                .setAnimation(MenuAnimation.SHOWUP_TOP_LEFT)
                .setCircularEffect(CircularEffect.BODY)
                .setMenuRadius(10f)
                .setMenuShadow(10f)
                .setTextColor(context.getColor(ResourceTable.Color_md_grey_800))
                .setTextSize(12)
                .setTextGravity(TextAlignment.CENTER)
                .setSelectedTextColor(Color.WHITE.getValue())
                .setMenuColor(Color.WHITE.getValue())
                .setSelectedMenuColor(context.getColor(ResourceTable.Color_colorPrimary))
                .setOnMenuItemClickListener(onMenuItemClickListener)
                .setOnDismissListener(onDismissedListener)
                .setPreferenceName("HamburgerPowerMenu")
                .setInitializeRule(Lifecycle.Event.ON_START, 0)
                .build();
    }

    public static PowerMenu getDialogPowerMenu(Context context, ILifecycle lifecycleOwner) {
        return new PowerMenu.Builder(context)
                .setHeaderView(ResourceTable.Layout_layout_dialog_header)
                .setFooterView(ResourceTable.Layout_layout_dialog_footer)
                .addItem(new PowerMenuItem("This is DialogPowerMenu", false))
                .setLifecycle(lifecycleOwner)
                .setAnimation(MenuAnimation.SHOW_UP_CENTER)
                .setCircularEffect(CircularEffect.BODY)
                .setMenuRadius(10f)
                .setMenuShadow(10f)
                .setPadding(14)
                .setWidth(600)
                .setMenuAligment(LayoutAlignment.CENTER)
                .setSelectedEffect(false)
                .build();
    }

    public static TransPowerMenu getProfilePowerMenu(
            Context context,
            ILifecycle lifecycleOwner,
            OnMenuItemClickListener<PowerMenuItem> onMenuItemClickListener) {
        return new TransPowerMenu.Builder(context)
                .setHeaderView(ResourceTable.Layout_item_title_header)
                .addItem(new PowerMenuItem("Profile", false))
                .addItem(new PowerMenuItem("Board", false))
                .addItem(new PowerMenuItem("Logout", false))
                .setLifecycle(lifecycleOwner)
                .setAnimation(MenuAnimation.SHOWUP_TOP_RIGHT)
                .setCircularEffect(CircularEffect.BODY)
                .setMenuRadius(10f)
                .setMenuShadow(10f)
                .setTextColor(context.getColor(ResourceTable.Color_md_grey_800))
                .setTextGravity(TextAlignment.CENTER)
                .setMenuColor(Color.BLACK.getValue())
                .setSelectedEffect(false)
                .setShowBackground(false)
                .setFocusable(true)
                .setOnMenuItemClickListener(onMenuItemClickListener)
                .build();
    }

    public static CustomPowerMenu<String, CenterMenuAdapter> getWritePowerMenu(
            Context context,
            ILifecycle lifecycleOwner,
            OnMenuItemClickListener<String> onMenuItemClickListener) {
        return new CustomPowerMenu.Builder<>(context, new CenterMenuAdapter())
                .addItem("Novel")
                .addItem("Poetry")
                .addItem("Art")
                .addItem("Journals")
                .addItem("Travel")
                .setILifecycle(lifecycleOwner)
                .setAnimation(MenuAnimation.FADE)
                .setCircularEffect(CircularEffect.BODY)
                .setMenuRadius(10f)
                .setMenuShadow(10f)
                .setOnMenuItemClickListener(onMenuItemClickListener)
                .setMenuAligment(LayoutAlignment.CENTER)
                .build();
    }

    public static CustomPowerMenu<String, CenterMenuAdapter> getAlertPowerMenu(
            Context context,
            ILifecycle lifecycleOwner,
            OnMenuItemClickListener<String> onMenuItemClickListener) {
        return new CustomPowerMenu.Builder<>(context, new CenterMenuAdapter())
                .addItem("You need to login!")
                .setILifecycle(lifecycleOwner)
                .setAnimation(MenuAnimation.ELASTIC_CENTER)
                .setCircularEffect(CircularEffect.BODY)
                .setMenuRadius(10f)
                .setMenuShadow(10f)
                .setFocusable(true)
                .setMenuAligment(LayoutAlignment.CENTER)
                .setOnMenuItemClickListener(onMenuItemClickListener)
                .setOnBackgroundClickListener(view -> {
                })
                .build();
    }

    public static PowerMenu getIconPowerMenu(
            Context context,
            ILifecycle lifecycleOwner,
            OnMenuItemClickListener<PowerMenuItem> onMenuItemClickListener) {
        return new PowerMenu.Builder(context)
                .addItem(new PowerMenuItem("WeChat", ResourceTable.Media_ic_wechat))
                .addItem(new PowerMenuItem("Facebook", ResourceTable.Media_ic_facebook))
                .addItem(new PowerMenuItem("Twitter", ResourceTable.Media_ic_twitter))
                .addItem(new PowerMenuItem("Line", ResourceTable.Media_ic_line))
                .addItem(new PowerMenuItem("Other"))
                .setLifecycle(lifecycleOwner)
                .setOnMenuItemClickListener(onMenuItemClickListener)
                .setAnimation(MenuAnimation.FADE)
                .setMenuRadius(7)
                .setMenuShadow(7)
                .setIsMaterial(true) // 设置带边框的dialog
                .setStrokColor(ResourceTable.Color_md_deep_orange_300) // 设置带边框的dialog
                .build();
    }

    public static CustomPowerMenu<NameCardMenuItem, CustomDialogMenuAdapter> getCustomDialogPowerMenu(
            Context context, ILifecycle lifecycleOwner) {
        return new CustomPowerMenu.Builder<>(context, new CustomDialogMenuAdapter())
                .setHeaderView(ResourceTable.Layout_layout_custom_dialog_header)
                .setFooterView(ResourceTable.Layout_layout_custom_dialog_footer)
        .addItem(
            new NameCardMenuItem(
                getPixelMapDrawable(context, ResourceTable.Media_face3),
                "Sophie",
                context.getString(ResourceTable.String_board3))
        )
                .setILifecycle(lifecycleOwner)
                .setAnimation(MenuAnimation.SHOW_UP_CENTER)
                .setCircularEffect(CircularEffect.BODY)
                .setWidth(800)
                .setMenuRadius(10f)
                .setMenuShadow(10f)
                .setMenuAligment(LayoutAlignment.CENTER)
                .build();
    }

    /**
     * 通过资源id获取路径
     *
     * @param context 上下文
     * @param id      资源id
     * @return 资源路径
     */
    public static String getPathById(Context context, int id) {
        String path = "";
        if (context == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new PowerMenuUtils().getClass().getName()), "getPathById -> get null context");
            return path;
        }
        ResourceManager manager = context.getResourceManager();
        if (manager == null) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new PowerMenuUtils().getClass().getName()), "getPathById -> get null ResourceManager");
            return path;
        }
        try {
            path = manager.getMediaPath(id);
        } catch (IOException | NotExistException | WrongTypeException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new PowerMenuUtils().getClass().getName()), "getPathById: " + e.getMessage());
        }
        return path;
    }

    /**
     * get the pixel map
     *
     * @param context the context
     * @param id      the id
     * @return the pixel map
     */
    public static Optional<PixelMap> getPixelMap(Context context, int id) {
        String path = getPathById(context, id);
        if (path.isEmpty()) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new PowerMenuUtils().getClass().getName()), "getPixelMap -> get empty path");
            return Optional.empty();
        }
        RawFileEntry assetManager = context.getResourceManager().getRawFileEntry(path);
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/png";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        try {
            Resource asset = assetManager.openRawFile();
            ImageSource source = ImageSource.create(asset, options);
            return Optional.ofNullable(source.createPixelmap(decodingOptions));
        } catch (IOException e) {
            HiLog.error(new HiLogLabel(HiLog.LOG_APP, 0, new PowerMenuUtils().getClass().getName()), "getPixelMap -> IOException");
        }
        return Optional.empty();
    }

    /**
     * get the Pixel Map Element
     *
     * @param context the context
     * @param resId   the res id
     * @return the Pixel Map Element
     */
    public static PixelMapElement getPixelMapDrawable(Context context, int resId) {
        Optional<PixelMap> optional = getPixelMap(context, resId);
        return optional.map(PixelMapElement::new).orElse(null);
    }

}
